define([
    'app',
    'angular-localForage'
], function (app) {
    'use strict';
    app.factory('audioData', ['$http', '$rootScope', '$localForage', function ($http, $rootScope, $localForage) {
        var gMinHeight = 1000;
        var gMaxHeight = -1000;
        var canvasWidth = 720;
        var canvasHeight = 120;
        var gRecording = false;
        var gHeights = [0.475, 3.2, 2.133, 2.494, 1.98, 1.952, 1.046, 0.174, 0.071, 1.256, 0.704, 0.2, 0, 0.3, 0.15, 2.124, 1.58, 0.061, 0, 1.374, 1.435, 0.6];
        var lastData = [];
        var gObject;
        var BIN_COUNT = 512;
        var LENGTH = 30;
        var audioData = {
            loadData:function(){},
            loadDataByCode:function(){},
            wavUrl:'',
        };
        var beautifyHeights = function (heights, minHeight, maxHeight) {
            var gLast = 0;
            var scale = 2 / (maxHeight);
            var newHeights = [];
            var threshold = 0.4;
            var startPos = 0;
            var endPos = 0;
            var wavUrl;
            for (var i = 0; i < heights.length; i++) {

                
                var height = parseFloat((scale * (heights[i])).toFixed(3));
                newHeights.push(height);
                gLast = height;


            }
            //newHeights = newHeights.slice(startPos, endPos + 1);
            return newHeights;
        };

        function onAnalyseDone(wavUrl, waveHeights, localId) {
            gHeights = beautifyHeights(gHeights, gMinHeight, gMaxHeight);
            var warning = false;
            if (gHeights.length < 10) {//Invalid data
                gRecording = false;
                warning = true;
            }
            window.gHeights = gHeights;
            var id = wavUrl.slice(7, wavUrl.length - 4);
            $rootScope.$emit('waveform', waveHeights, gHeights, wavUrl, localId, warning);
            // $http.get('http://www.malianghang.cn/getshortid?id=' + id).success(function(res){
            //      $rootScope.$emit('waveform', waveHeights, gHeights, wavUrl, res, localId);
            // });

        }

        var getContext = function () {
            var canvas = document.getElementById("wave-form");
            if (canvas) {
                var ctx = canvas.getContext("2d");
                ctx.lineWidth = 2;
                ctx.strokeStyle = 'rgba(0,0,0,1)';
                return ctx;
            }
            return false;
        }
        var drawStart = function () {
            var ctx = getContext();
            if (ctx) {
                ctx.clearRect(0, 0, canvasWidth, 2 * canvasHeight);
                ctx.beginPath();
                ctx.moveTo(0, canvasHeight);
            }
        };
        var drawEnd = function () {
            var ctx = getContext();
            if (ctx) {
                ctx.lineTo(canvasWidth, canvasHeight);
                ctx.stroke(); // 以线条显示轨迹
            }
        };
        
        var drawLine = function (start, waveHeights, count, maxHeight) {

            var count = count || LENGTH * BIN_COUNT;
            var scale = canvasHeight * 0.3 / (maxHeight);
            var step = canvasWidth * 1.0 / (count);
            var ctx = getContext();
            if (ctx) {
                for (var i = 1; i < waveHeights.length + 1; i++) {
                    ctx.lineTo((i) * step, canvasHeight + scale * (waveHeights[i]));
                    // setTimeout(function(i){
                    //     return function(){
                    //         ctx.lineTo((i) * step, canvasHeight + scale * (waveHeights[i]));
                    //         if(i%5==4) ctx.stroke();
                    //     }
                        
                    // }(i), i);

                    
                }
                ctx.stroke();
                
            }
        };
        var draw = function (start, waveHeights, count, maxHeight) {
            var count = count || LENGTH * BIN_COUNT;
            var scale = canvasHeight * 0.8 / (maxHeight);
            var step = canvasWidth * 1.0 / (count + 1);
            var ctx = getContext();
            if (ctx) {
                for (var i = 0; i < waveHeights.length; i++) {
                    ctx.lineTo((start + i) * step, canvasHeight + scale * (waveHeights[i]));
                }
                ctx.stroke();
            }
        };
        function loadDataByCode(code){
            $http({
                method: 'GET',
                url: 'http://www.malianghang.cn/getmediaid?id=' + code
            }).then(function (res) {
                console.log('/wxmp3/' + res.data + '.wav');
                loadData('/wxmp3/' + res.data + '.wav');
            });

        }
        function trim(data){
            console.log(data)
            var startPos = -1, endPos = 0;
            var threshold = 5;
            for (var i = 0; i < data.length; i++) {
                var value = Math.abs(data[i] - 200);
                if(startPos == -1 && value > threshold) startPos = i;
                if(value > threshold) endPos = i; 
            }
            return data.slice(startPos - 20, endPos + 20);
        }
        
        /**
         * get wav from server and analyse
         */
        function loadData(url, localId) {
            // var log = document.getElementById("log");
            // log.innerHTML = url;
            audioData.wavUrl = url;
            gMinHeight = 1000;
            gMaxHeight = -1000;
            var startPos = -1;
            var endPos = -1;


            function onLoad(data){

                var interval = parseInt(data.length / LENGTH);
                var waveInterval = parseInt(data.length / 150);
                var sum = 0;
                var count = 0;
                var maxHeight = data.pop();
                maxHeight = -1000;
                lastData = data;
                gHeights = [];
                var waveHeights = [];

                drawStart();
                data = trim(data);
                for (var i = 0; i < data.length; i++) {
                    
                    var value = data[i] - 200;
                    if (i % waveInterval == waveInterval - 1) {
                        waveHeights.push(value);
                        var offset = value;
                        waveHeights.push(-value);

                        if(maxHeight < Math.abs(value)) maxHeight = Math.abs(value);
                    }
                    
                    if (value > 0) {
                        sum += value;
                        count += 1;
                    }

                    if (i % interval == interval - 1) {
                        var current;
                        if (count)
                            current = sum * 1.0 / count;
                        else
                            current = 0;

                        // if(startPos == -1 && current > 2.5) startPos = gHeights.length;
                        // if(current > 2.5) endPos = gHeights.length; 

                        if(gHeights.length % 2) gHeights.push(current);
                        else gHeights.push(-current);
                        if (current >= 0) {
                            gMinHeight = gMinHeight > current ? current : gMinHeight;
                            gMaxHeight = gMaxHeight < current ? current : gMaxHeight;
                        }

                        sum = 0;
                        count = 0;

                    }
                }
                //gHeights = gHeights.slice(startPos, endPos);
                //TODO: move to recorder directive
                drawLine(0, waveHeights, waveHeights.length, maxHeight);
                onAnalyseDone(url, waveHeights, localId);
            }
            $localForage.getItem(url).then(function(data) {
                if(data != null) {
                    onLoad(data);
                    console.log('cache');
                } else {
                    console.log('http');
                    $http({
                        method: 'GET',
                        url: 'http://www.malianghang.cn/waveform?wav=' + url.slice(7)
                    }).then(function (res) {
                        onLoad(res.data);
                        $localForage.setItem(url, res.data);
                    }, function (error) {
                        console.log(error);
                    });
                }
            });

          


        }
        audioData.loadData = loadData;
        audioData.loadDataByCode = loadDataByCode;
        window.gHeights = gHeights;
        window.gRecording = gRecording;


        return audioData;
    }]);

});
